
package game.control {
	import common.debug.Debug;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import game.manager.LayerManager;
	import game.model.SceneModel;
	import game.model.vo.SceneVO;
	import game.view.SceneView;
	
	import utils.Singleton;
	
	
	/**
	 * Scene
	 *
	 * @author chris
	 *
	 * Apr 19, 2013
	 */
	public class Scene extends Singleton {
		
		private var sceneView:SceneView;
		private var model:SceneModel;
		
		public function Scene()
		{
			super();
			model = SceneModel.inst;
			sceneView = new SceneView();
			LayerManager.inst.sceneLayer.addChild(sceneView);
		}
		
		public static function get inst():Scene {
			return Singleton.getInstanceOrCreate(Scene) as Scene;
		}
		
		public function enterScene(sceneId:int):void {
			loadSceneBin(sceneId);
		}
		
		private var loader:URLLoader;
		public function loadSceneBin(sceneId:int):void {
			loader = new URLLoader();
			var url:URLRequest = new URLRequest("assets/scene/"+sceneId+"/"+sceneId+".bin");
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE,onLoadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onError);
			loader.load(url);
		}
		
		private function onError(evt:IOErrorEvent):void {
			Debug.log(evt.toString());
		}
		
		public function onLoadComplete(event:Event):void {
			var bytes:ByteArray = loader.data;
			var sceneVO:SceneVO = new SceneVO();
			sceneVO.id = 4;
			sceneVO.width = bytes.readInt();
			sceneVO.height = bytes.readInt();
			sceneVO.tileWidth = bytes.readShort();
			sceneVO.tileHeight = bytes.readShort();
			sceneVO.gridWith = bytes.readShort();
			sceneVO.gridHeight = bytes.readShort();
			sceneVO.grids = new Array();
			var num:int = bytes.readInt();
			for(var i:int=0;i<num;i++) {
				sceneVO.grids.push(bytes.readShort());
			}
			
			model.sceneVO = sceneVO;	
			model.center.x = model.sceneVO.width/2;
			model.center.y = model.sceneVO.height/2;
			
			sceneView.buildScene(sceneVO);
		}
	}
}